//
//  ShowQRViewController.m
//  QRBuildScan
//
//  Created by  on 12-1-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ShowQRViewController.h"
#import "QREncoder.h"
#import "DataMatrix.h"

#define QRImageTag 0x11

@implementation ShowQRViewController
@synthesize m_TranStr;
@synthesize m_SaveQRImgButton;
-(void) setM_TranStr:(NSString *)p_TranStr{
    [m_TranStr release];
    m_TranStr = nil;
    m_TranStr = p_TranStr;
    [m_TranStr retain];
    DataMatrix* qrMatrix = [QREncoder encodeWithECLevel:QR_ECLEVEL_AUTO version:QR_VERSION_AUTO string:m_TranStr];
    
    int qrcodeImageDimension = 300;
    //then render the matrix
    UIImage* qrcodeImage = [QREncoder renderDataMatrix:qrMatrix imageDimension:qrcodeImageDimension];
    
    //put the image into the view
    UIImageView* qrcodeImageView = [[UIImageView alloc] initWithImage:qrcodeImage];
    qrcodeImageView.tag =QRImageTag;
    CGRect parentFrame = self.view.frame;
    parentFrame.origin.x = 10;
    parentFrame.origin.y = 30;
    parentFrame.size =CGSizeMake(qrcodeImageDimension, qrcodeImageDimension);
    qrcodeImageView.frame =parentFrame;
    [self.view addSubview:qrcodeImageView];
    [qrcodeImageView release];
    
    m_SaveQRImgButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [m_SaveQRImgButton setImage:[UIImage imageNamed:@"saveqr.png"] forState:UIControlStateNormal];
    m_SaveQRImgButton.frame =CGRectMake(254, 7, 60, 30);
    [m_SaveQRImgButton addTarget:self action:@selector(saveQRImage) forControlEvents:UIControlEventTouchUpInside];
    [m_SaveQRImgButton retain];
}

-(void) dealloc{
    [m_SaveQRImgButton removeFromSuperview];
    [m_SaveQRImgButton release];
    [m_TranStr release];
    [super dealloc];
}

-(void) saveQRImage{
    NSFileManager* tFileMan = [NSFileManager defaultManager];
    NSString* tMenuPathDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSUserDefaults* tDefaults =[NSUserDefaults standardUserDefaults];
    int index = [[tDefaults objectForKey:@"addcount"] intValue];
    NSString* tSavePath = [tMenuPathDoc stringByAppendingPathComponent:@"QRSave"];
    [tFileMan createDirectoryAtPath:tSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString* tSaveIndexPath = [tSavePath stringByAppendingPathComponent:[NSString stringWithFormat:@"qrimg%d",index+1]];
    [tDefaults setValue:[NSNumber numberWithInt:index+1] forKey:@"addcount"];
    UIImageView* tSaveIV = (UIImageView*)[self.view viewWithTag:QRImageTag];
    [UIImagePNGRepresentation(tSaveIV.image) writeToFile:tSaveIndexPath atomically:YES];
    
    UIAlertView* tAlert =[[UIAlertView alloc] initWithTitle:@"提示" message:@"保存QR图成功" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [tAlert show];
    [tAlert release];
}

@end
